#coding=utf-8

from django.shortcuts import render_to_response
from django.template import RequestContext
from storage.models import *
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.utils import simplejson  
from storage.RuleInterface import addOne, deleteOne, updateOne, getAll, getOne, changeStatus



        


# 添加一条规则，从json格式
# 成功返回规则的json形式，失败返回错误原因
@csrf_exempt
def addRule(request):
    if request.method == 'POST':
        req = simplejson.loads(request.body)
#         print req
        rule = addOne(req)
        if rule:
            return HttpResponse(rule.to_json())
        else:
            return HttpResponse('Please check rule formate')          
        
    else:
        return HttpResponse('Wrong method.Please use Post method.')
        
        
        
# 更新一条规则通过完成的json描述
# 成功返回规则的200，失败返回错误原因
@csrf_exempt
def updateRule(request):
    if request.method == 'POST':
        req = simplejson.loads(request.body)
        print req
        if update(req):
            return HttpResponse('200')
        else: 
            return HttpResponse('Please check rule formate') 
    else:
        return HttpResponse('Wrong method.Please use Post method.')
        
# 删除一条规则，json包含
# id:规则id
# 成功返回200，失败返回原因
@csrf_exempt
def deleteRule(request):
    if request.method == 'POST':
        req = simplejson.loads(request.body)
        if deleteOne(req):
            return HttpResponse('200')
        else: 
            return HttpResponse('Please check rule id')  
    else:
        return HttpResponse('Wrong method.Please use Post method.')


# 修改规则状态，json格式
# id:规则id
# status：状态
# 成功返回200，失败返回原因
@csrf_exempt
def rulestatus(request):
    if request.method == 'POST':
        req = simplejson.loads(request.body)
        if changeStatus(req):
            return HttpResponse(200)
        else: 
            return HttpResponse('Please check change info.')  
    else:
        return HttpResponse('Wrong method.Please use Post method.')
    
    
# 获取所有规则的json格式
# 成功返回所有规则的json格式描述，失败返回原因
@csrf_exempt  
def Allrules(request):
    if request.method == 'POST':
        rules = getAll()
        if rules:
            return HttpResponse(rules.to_json())
        else:
            return HttpResponse('No rules.')
    else:
        return HttpResponse('Wrong method.Please use Post method.')



            